#!/usr/bin/env python

"""
========
PyHP App
========

This class rappresents the PyHP application.
It is able to parse ".pyhp" pages inside the WSGI environment.
"""

from framework import PyHPFrameWork
import sys, os

class PyHPApp ( object ):
	def _handle_pyhp ( self, pyhp, res, environ ):
		old_dir = ''
		self._get_stdout ( res )

		if environ [ 'pyhp_target_path' ]:
			old_dir = os.getcwd ()
			os.chdir ( environ [ 'pyhp_target_path' ] )
		

		# FIXME:  se al posto di questa linea metto il blocco
		#	  try qui sotto ho i loop infiniti
		#environ [ 'pyhp-exec' ].read ( environ [ 'pyhp_target_name' ] )

		try:
			environ [ 'pyhp-exec' ].read ( environ [ 'pyhp_target_name' ] )
		except:
			raise
		finally:
			if old_dir: 
				os.chdir ( old_dir )
				sys.stdout = self._old_stdout

		return 0



	def _handle_unkn ( self, pyhp, res, environ ):
		pass

	def _handle_file ( self, pyhp, res, environ ):
		fname = os.path.join ( environ.get ( 'pyhp_target_path', '' ), environ [ 'pyhp_target_name' ] )

		import mimetypes
		pyhp.set_header (  'Content-Type', mimetypes.guess_type ( environ [ 'pyhp_target_name' ] ) [ 0 ] )
		res.append ( file ( fname ).read ()  )

	def _handle_dir ( self, pyhp, res, environ ):
		pass

	def _get_stdout ( self, dest ):
		class my_stdout ( object ):
			def __init__ ( self, dest ):
				self._dest = dest

			def write ( self, txt ):
				self._dest.append ( txt )
				
		self._old_stdout = sys.stdout
		sys.stdout = my_stdout ( dest )

	def __call__ ( self, environ, start_response ):
		pyhp = environ [ 'pyhp' ]
		pyhp.set_header ( 'Content-Type', 'text/html' )

		self.environ = environ
		self.start_response = start_response

		res = []

		handler = self._handlers.get ( environ [ 'pyhp_target_type' ] )
		while handler:
			run_again = handler ( pyhp, res, environ )
			#pyhp.log.debug ( "+++ HANDLER: %s - AGAIN: %s\n" % ( str ( handler ), run_again ) )

			if not run_again:
				break

			handler = self._handlers.get ( environ [ 'pyhp_target_type' ] )

		return res

	def set_handler ( self, handler, func ):
		self._handlers [ handler.lower () ] = func

	def __init__ ( self ):
		self._handlers = {
			"dir" : self._handle_dir,
			"unkn" : self._handle_unkn,
			"file" : self._handle_file,
			"pyhp" : self._handle_pyhp
		}
